package org.oschina.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.oschina.Constants;
import org.oschina.helper.ThreadVariableHelper;
import org.oschina.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class ThreadVariableHandleInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private ThreadVariableHelper threadVariableHelper;
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
	{
		threadVariableHelper.remove();
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		threadVariableHelper.set(Constants.THREAD_VARIABLE_IP, getIp(request));
		threadVariableHelper.set(Constants.THREAD_VARIABLE_TOKEN, getToken(request));
		return true;
	}
	
	/**
	 * 获得IP
	 * @return
	 */
	private String getIp(HttpServletRequest request)
	{
		return HttpUtil.getIp(request);
	}
	
	/**
	 * 获得令牌
	 * @return
	 */
	private String getToken(HttpServletRequest request)
	{
		return request.getParameter("token");
	}
}